package risk.control.application.utils;

import android.util.SparseArray;
import android.view.View;

/**
 * @className: ViewHoldeUtils
 * @description: 对于常用Adapter的viewholder工具类
 * @author: hm
 * @version: 1.0
 * @CreateTime: 2016年04月15日
 */
public class ViewHolderUtils {

    /**
     * 根据id获取布局中相应的控件
     *
     * @param view xml布局实例化后的根节点对象
     * @param id   控件的id
     * @return 目标控件
     */
//    public static <T extends View> T get(View view, int id) {
//        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
//        if (viewHolder == null) {
//            viewHolder = new SparseArray<View>();
//            view.setTag(viewHolder);
//        }
//        View childView = viewHolder.get(id);
//        if (childView == null) {
//            childView = view.findViewById(id);
//            viewHolder.put(id, childView);
//        }
//        return (T) childView;
//    }
    @SuppressWarnings("unchecked")
    public static <T extends View> T get(View parent, int id) {
        SparseArray<View> views = new SparseArray<>();
        View view = views.get(id);
        if (view == null) {
            view = parent.findViewById(id);
            if (view == null) {
                throw new IllegalArgumentException("No view found with ID " + id);
            }
            views.put(id, view);
        }
        return (T) view;
    }
}
